/**
 * 通道配置工具 - 海水DIY灯通道定义
 * 基于玩家模式页定义标准，统一所有页面和组件的通道定义
 */

// 导入日志工具
const { logger } = require('./logger')
// 导入存储服务
const storageService = require('../services/storage')

/**
 * 获取默认通道配置 - 标准10通道
 * @returns {Array} 默认通道配置数组
 */
function getDefaultChannelConfigs() {
  // 海水DIY灯固定为10通道
  return [
    {
      name: '红色',
      color: '#FF0000',
      enabled: true,
    },
    {
      name: '绿色',
      color: '#00FF00',
      enabled: true,
    },
    {
      name: '蓝色',
      color: '#0000FF',
      enabled: true,
    },
    {
      name: '暖白',
      color: '#FFD700',
      enabled: true,
    },
    {
      name: '浅蓝',
      color: '#ADD8E6',
      enabled: true,
    },
    {
      name: '宝蓝',
      color: '#4169E1',
      enabled: true,
    },
    {
      name: '紫色',
      color: '#990099',
      enabled: true,
    },
    {
      name: '紫外',
      color: '#6200EA',
      enabled: true,
    },
    {
      name: '月光白',
      color: '#E0E0E0',
      enabled: true,
    },
    {
      name: '月光蓝',
      color: '#87CEEB',
      enabled: true,
    }
  ]
}

/**
 * 获取通道命名映射
 * @returns {Object} 通道命名映射表
 */
function getChannelNameMapping() {
  return {
    red: "红光",
    green: "绿光",
    blue: "蓝光",
    white: "白光", // 或 warmWhite
    lightBlue: "浅蓝",
    royalBlue: "宝蓝",
    purple: "紫光",
    uv: "紫外",
    moonWhite: "月光白",
    moonBlue: "月光蓝"
  }
}

/**
 * 加载实体(设备或编组)的通道配置
 * @param {string} entityId 实体ID
 * @param {boolean} isGroup 是否为编组
 * @param {string} deviceType 设备类型
 * @returns {Object} 通道配置对象，包含channelConfigs, channelEnabled, channelNames, channelColors
 */
function loadEntityChannelConfigs(entityId, isGroup, deviceType = 'seawater_diy_lamp') {
  try {
    if (!entityId) {
      logger.error('loadEntityChannelConfigs: 没有传入有效的 entityId');
      return getDefaultConfigs();
    }

    // 从存储中获取通道配置
    const modeSettingData = storageService.getModeSettingData(entityId, isGroup, deviceType);
    let channelConfigs = [];

    if (modeSettingData?.channelConfigs && Array.isArray(modeSettingData.channelConfigs)) {
      channelConfigs = modeSettingData.channelConfigs;
    } else {
      // 日志记录配置获取失败
      /*logger.channelConfig('通道配置获取失败，使用默认配置', {
        entityId, 
        isGroup, 
        deviceType,
        hasConfig: !!modeSettingData?.channelConfigs,
        isArray: Array.isArray(modeSettingData?.channelConfigs)
      });*/
      channelConfigs = getDefaultChannelConfigs();
    }

    // 确保有10个通道
    if (channelConfigs.length !== 10) {
      // 日志记录通道数量不符
      /*logger.channelConfig('通道配置数量不符，使用默认配置', {
        entityId,
        isGroup,
        deviceType,
        channelCount: channelConfigs.length
      });*/
      channelConfigs = getDefaultChannelConfigs();
    }

    // 提取通道启用状态
    const channelEnabled = {
      red: channelConfigs[0]?.enabled !== false,
      green: channelConfigs[1]?.enabled !== false,
      blue: channelConfigs[2]?.enabled !== false,
      white: channelConfigs[3]?.enabled !== false,
      lightBlue: channelConfigs[4]?.enabled !== false,
      royalBlue: channelConfigs[5]?.enabled !== false,
      purple: channelConfigs[6]?.enabled !== false,
      uv: channelConfigs[7]?.enabled !== false,
      moonWhite: channelConfigs[8]?.enabled !== false,
      moonBlue: channelConfigs[9]?.enabled !== false
    };

    // 提取通道名称和颜色
    const channelNames = {};
    const channelColors = {};
    const channelKeys = ['red', 'green', 'blue', 'white', 'lightBlue', 'royalBlue', 'purple', 'uv', 'moonWhite', 'moonBlue'];

    // 遍历通道配置，提取自定义名称和颜色
    channelConfigs.forEach((config, index) => {
      if (index < channelKeys.length) {
        const key = channelKeys[index];
        // 尝试各种可能的名称字段
        if (config.customName) {
          channelNames[key] = config.customName;
        } else if (config.name) {
          channelNames[key] = config.name;
        } else if (config.displayName) {
          channelNames[key] = config.displayName;
        }
        
        // 尝试各种可能的颜色字段
        if (config.color) {
          channelColors[key] = config.color;
        } else if (config.colorValue) {
          channelColors[key] = config.colorValue;
        } else if (config.displayColor) {
          channelColors[key] = config.displayColor;
        }
      }
    });

    return {
      channelConfigs,
      channelEnabled,
      channelNames,
      channelColors
    };
  } catch (e) {
    logger.error('加载实体通道配置失败', e);
    return getDefaultConfigs();
  }
}

/**
 * 获取默认配置
 * @returns {Object} 默认的通道配置
 */
function getDefaultConfigs() {
  const channelConfigs = getDefaultChannelConfigs();
  const channelNames = getChannelNameMapping();
  const channelEnabled = {
    red: true,
    green: true,
    blue: true,
    white: true,
    lightBlue: true,
    royalBlue: true,
    purple: true,
    uv: true,
    moonWhite: true,
    moonBlue: true
  };
  
  const channelColors = {
    red: '#FF0000',
    green: '#00FF00',
    blue: '#0000FF',
    white: '#FFD700',
    lightBlue: '#ADD8E6',
    royalBlue: '#4169E1',
    purple: '#990099',
    uv: '#6200EA',
    moonWhite: '#E0E0E0',
    moonBlue: '#87CEEB'
  };

  return {
    channelConfigs,
    channelEnabled,
    channelNames,
    channelColors
  };
}

/**
 * 应用通道配置到设备对象
 * @param {Object} device 设备或编组对象
 * @param {Array} channelConfigs 通道配置数组
 * @returns {Object} 更新后的设备或编组对象
 */
function applyChannelConfigsToDevice(device, channelConfigs) {
  if (!device || !Array.isArray(channelConfigs) || channelConfigs.length < 10) {
    return device;
  }

  const updatedDevice = JSON.parse(JSON.stringify(device));
  
  // 设置通道启用状态
  updatedDevice.redEnabled = channelConfigs[0]?.enabled !== false;
  updatedDevice.greenEnabled = channelConfigs[1]?.enabled !== false;
  updatedDevice.blueEnabled = channelConfigs[2]?.enabled !== false;
  updatedDevice.warmWhiteEnabled = channelConfigs[3]?.enabled !== false;
  updatedDevice.lightBlueEnabled = channelConfigs[4]?.enabled !== false;
  updatedDevice.royalBlueEnabled = channelConfigs[5]?.enabled !== false;
  updatedDevice.purpleEnabled = channelConfigs[6]?.enabled !== false;
  updatedDevice.uvEnabled = channelConfigs[7]?.enabled !== false;
  updatedDevice.moonWhiteEnabled = channelConfigs[8]?.enabled !== false;
  updatedDevice.moonBlueEnabled = channelConfigs[9]?.enabled !== false;
  
  // 设置通道显示颜色
  updatedDevice.redColor = channelConfigs[0]?.color || '#FF0000';
  updatedDevice.greenColor = channelConfigs[1]?.color || '#00FF00';
  updatedDevice.blueColor = channelConfigs[2]?.color || '#0000FF';
  updatedDevice.warmWhiteColor = channelConfigs[3]?.color || '#FFD700';
  updatedDevice.lightBlueColor = channelConfigs[4]?.color || '#ADD8E6';
  updatedDevice.royalBlueColor = channelConfigs[5]?.color || '#4169E1';
  updatedDevice.purpleColor = channelConfigs[6]?.color || '#990099';
  updatedDevice.uvColor = channelConfigs[7]?.color || '#6200EA';
  updatedDevice.moonWhiteColor = channelConfigs[8]?.color || '#E0E0E0';
  updatedDevice.moonBlueColor = channelConfigs[9]?.color || '#87CEEB';
  
  // 设置通道显示名称（如果有自定义名称）
  if (channelConfigs[0]?.name) updatedDevice.redName = channelConfigs[0].name;
  if (channelConfigs[1]?.name) updatedDevice.greenName = channelConfigs[1].name;
  if (channelConfigs[2]?.name) updatedDevice.blueName = channelConfigs[2].name;
  if (channelConfigs[3]?.name) updatedDevice.warmWhiteName = channelConfigs[3].name;
  if (channelConfigs[4]?.name) updatedDevice.lightBlueName = channelConfigs[4].name;
  if (channelConfigs[5]?.name) updatedDevice.royalBlueName = channelConfigs[5].name;
  if (channelConfigs[6]?.name) updatedDevice.purpleName = channelConfigs[6].name;
  if (channelConfigs[7]?.name) updatedDevice.uvName = channelConfigs[7].name;
  if (channelConfigs[8]?.name) updatedDevice.moonWhiteName = channelConfigs[8].name;
  if (channelConfigs[9]?.name) updatedDevice.moonBlueName = channelConfigs[9].name;
  
  // 添加强制刷新标记
  updatedDevice._forceRefresh = new Date().getTime();
  
  return updatedDevice;
}

/**
 * 保存通道配置
 * @param {string} entityId 实体ID
 * @param {Array} channelConfigs 通道配置数组 
 * @param {boolean} isGroup 是否为编组
 * @param {string} deviceType 设备类型
 */
function saveChannelConfigs(entityId, channelConfigs, isGroup = false, deviceType = 'seawater_diy_lamp') {
  try {
    if (!entityId) {
      logger.error('saveChannelConfigs: 没有有效的 entityId');
      return false;
    }

    // 记录通道配置保存操作
    /*logger.channelConfig('执行保存通道配置', {
      entityId: entityId, 
      deviceType: deviceType,
      isGroup: isGroup,
      channelCount: channelConfigs.length,
      storageKey: `${deviceType}_channelConfigs_${entityId}`
    });*/
    
    // 保存通道配置
    storageService.saveModeSettingData(
      entityId,
      { channelConfigs: channelConfigs },
      isGroup,
      deviceType
    );

    // 如果是编组，将通道配置同步到编组内的所有设备
    if (isGroup) {
      try {
        // 获取编组信息
        const groups = storageService.getGroups();
        const group = groups.find(g => g.id === entityId);
        
        if (group && Array.isArray(group.deviceIds)) {
          /*logger.channelConfig(`正在同步编组[${entityId}]的通道配置到${group.deviceIds.length}个设备`, {
            groupId: entityId,
            deviceCount: group.deviceIds.length
          });*/
          
          // 获取所有设备
          const devices = storageService.getDevices();
          
          // 遍历编组内的所有设备
          group.deviceIds.forEach(deviceId => {
            // 查找设备
            const device = devices.find(d => d.id === deviceId);
            
            // 确保设备存在且设备类型匹配
            if (device && device.deviceType === deviceType) {
              // 将编组的通道配置保存到设备
              storageService.saveModeSettingData(
                deviceId,
                { channelConfigs: channelConfigs },
                false, // 不是编组
                deviceType
              );
              
              // 设置设备特定的刷新标记
              wx.setStorageSync(`device_channel_updated_${deviceId}`, new Date().getTime());
              
              /*logger.channelConfig(`已同步编组[${entityId}]的通道配置到设备[${deviceId}]`, {
                deviceId: deviceId
              });*/
            } else if (!device) {
              logger.error(`同步通道配置失败: 编组[${entityId}]中的设备[${deviceId}]不存在`);
            } else if (device.deviceType !== deviceType) {
              logger.error(`同步通道配置失败: 编组[${entityId}]中的设备[${deviceId}]类型不匹配，预期:${deviceType}，实际:${device.deviceType}`);
            }
          });
        } else {
          logger.error(`同步通道配置失败: 编组[${entityId}]不存在或不包含有效的设备ID列表`);
        }
      } catch (syncError) {
        logger.error('同步编组通道配置到设备时发生错误', syncError);
        // 不阻止主流程，仅记录同步错误
      }
    }

    // 增强刷新机制 - 设置多个标志确保刷新
    wx.setStorageSync('refreshDeviceCardsFlag', new Date().getTime());
    wx.setStorageSync(`${deviceType}_channelConfig_updated_${entityId}`, new Date().getTime());

    return true;
  } catch (e) {
    logger.error('保存通道配置失败', e);
    return false;
  }
}

module.exports = {
  getDefaultChannelConfigs,
  getChannelNameMapping,
  loadEntityChannelConfigs,
  applyChannelConfigsToDevice,
  saveChannelConfigs,
  getDefaultConfigs
} 